package com.fucking.great.context.plun.template;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.fucking.great.context.TxnContext;
import com.fucking.great.context.exception.TxnRuntimeException;
import com.fucking.great.context.common.template.TemplateComponent;
import com.fucking.great.context.plun.BasePlug;
import com.fucking.great.context.util.GetMapDecorator;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 模板化组件
 * @see  cn.hutool.extra.template.TemplateConfig 如何设置配置 <br/>
 * <b></b>
 */
public class TemplatePlug extends BasePlug {
    public static final String PLUN_NAME = "template";
    public TemplatePlug(Map<String, String> config) {
        super( config,new String[]{
                TemplateComponent.class.getName(),
                "cn.hutool.extra.template.TemplateConfig.ResourceMode"
        });
    }

    @Override
    protected void initUserPlunMap(Map<String, Object> userPlun) {
        //
        GetMapDecorator<String, String> prefixConfig = this.getPrefixConfig(PLUN_NAME);
        //
        TemplateConfig config = getTemplateConfig(prefixConfig);
        //
        TemplateComponent templateComponent = TemplateComponent.getInstance(config);
        //
        userPlun.put(PLUN_NAME,templateComponent);
    }

    /**
     * 从配置中,获得TemplateConfig
     * @param prefixConfig
     * @return
     */
    public static final TemplateConfig getTemplateConfig(GetMapDecorator<String, String> prefixConfig) {
    /*
        设置config
     */
        TemplateConfig config = new TemplateConfig();
        //
        String charset = prefixConfig.getStr("charset", "UTF-8");
        config.setCharset(CharsetUtil.charset(charset));
        //
        String customEngine = prefixConfig.getStr("customEngine");
        if(StrUtil.isNotBlank(customEngine)){
            config.setCustomEngine(ClassUtil.loadClass(customEngine,false));
        }
        //
        String path = prefixConfig.getStr("path");
        if(StrUtil.isNotBlank(path)){
            config.setPath(path);
        }
        //
        String resourceMode = prefixConfig.getStr("resourceMode",
                TemplateConfig.ResourceMode.STRING.name());
        config.setResourceMode(TemplateConfig.ResourceMode.valueOf(resourceMode));
        return config;
    }



}
